package com.lagou.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Map;

import com.lagou.dao.UserDao;
import com.lagou.domain.User;
import com.lagou.service.UserService;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("user");
        resp.sendRedirect("index.html");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取所有的请求头名称
        Enumeration<String> enumeration = req.getHeaderNames();
        // 遍历
        while(enumeration.hasMoreElements()){
            // 取出元素名（请求头名称）
            String name = enumeration.nextElement();
            // 根据名称获取值
            String value = req.getHeader(name);
            System.out.println(name +" : "+ value);

        }
        Map<String,String[]> params = req.getParameterMap();
        System.out.println(params);

        System.out.println("---------用户请求登录---------");
        String username = req.getParameter("username");
        System.out.println("用户：" + username);
        String password = req.getParameter("password");
        System.out.println("密码：" + password);
        UserService us = new UserService();
        try {
            User user = us.login(username, password);
            if(user!=null){
                HttpSession session = req.getSession();
                session.setAttribute("user", user);
                resp.sendRedirect("loginSuccess.html");
            }
            else{
                resp.getWriter().println("用户名或密码错误！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }


    }
}
